<template>
  <div ref="target" class="xtx-infinite-loading">
    <div v-if="loading" class="loading">
      <span class="img"></span>
      <span class="text">正在加载...</span>
    </div>

    <div v-if="finished" class="none">
      <span class="img"></span>
      <span class="text">亲, 没有更多了</span>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'

export default {
  name: 'XtxInfiniteLoading',
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    finished: {
      type: Boolean,
      default: false
    }
  },
  setup(props, { emit }) {
    const target = ref(null)

    // 监听target是否进入可视区
    const { stop } = useIntersectionObserver(target,
      ([{ isIntersecting }]) => {
        if (isIntersecting) {
          console.log('进去可视区了')
          // 触发加载事件的条件: 请求加载完毕 loading: false, 但数据没有加载完毕 finished: false
          if (!props.loading && !props.finished) {
            // 发出一个事件     infinite 无穷
            emit('infinite')
          }

        }

      }, { threshold: 0.01 })
    return {
      target
    }
  }
}
</script>

<style lang="less" scoped>
.xtx-infinite-loading {

  .loading {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;

    .img {
      width: 50px;
      height: 50px;
      background: url(../../assets/images/load.gif) no-repeat center / contain;
    }

    .text {
      color: #999;
      font-size: 16px;
    }
  }

  .none {
    display: flex;
    align-items: center;
    height: 200px;
    justify-content: center;

    .img {
      width: 200px;
      height: 134px;
      background: url(../../assets/images/none.png) no-repeat center / contain;
    }

    .text {
      color: #999;
      font-size: 16px;
    }
  }
}
</style>
